package com.cardone.platform.authority.service;

import com.cardone.context.ContextHolder;
import com.cardone.context.DictionaryException;
import com.cardone.platform.usercenter.dto.UserDto;
import com.cardone.platform.usercenter.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2014/11/4.
 */
public class ShiroDbRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserDto user = (UserDto) principals.getPrimaryPrincipal();

        Map<String, List<String>> initMap = ContextHolder.getBean(RolePermissionService.class).findByUserId(user.getId());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        List<String> roleCodes = initMap.get("roleCodes");

        if (CollectionUtils.isNotEmpty(roleCodes)) {
            info.addRoles(roleCodes);
        }

        List<String> permissionCodes = initMap.get("permissionCodes");

        if (CollectionUtils.isNotEmpty(permissionCodes)) {
            info.addStringPermissions(permissionCodes);
        }

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

        UserDto findUser = new UserDto();

        if (StringUtils.isBlank(usernamePasswordToken.getUsername())) {
            throw new DictionaryException("用户名不能为空值!");
        }

        if (ArrayUtils.isEmpty(usernamePasswordToken.getPassword())) {
            throw new DictionaryException("密码不能为空值!");
        }

        findUser.setCode(usernamePasswordToken.getUsername());

        findUser.setPassword(new String(usernamePasswordToken.getPassword()));

        UserDto user = ContextHolder.getBean(UserService.class).login(findUser);

        if (user == null) {
            throw new UnknownAccountException();//没找到帐号
        }

        if ("2".equals(user.getValidCode())) {
            throw new LockedAccountException(); //帐号锁定
        }

        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
